package com.zj.leetcode.medium.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: algorithm
 * @description: 二叉树的层序遍历
 * 102 binary-tree-level-order-traversal
 * @author: Zhang Bo
 * @create: 2022-06-08 10:15:16
 **/
public class BinaryTreeLevelOrderTraversal {
    public static void main(String[] args) {
        Solution solution = new BinaryTreeLevelOrderTraversal().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * [3,9,20,null,null,15,7]
     */
    class Solution {

        List<List<Integer>> res = new ArrayList<>();

        public List<List<Integer>> levelOrder(TreeNode root) {
            levelOrder(root, 0);
            return res;
        }

        private void levelOrder(TreeNode node, int level) {
            if (node == null) {
                return;
            }

            List<Integer> list;
            if (res.size() < level + 1) {
                list = new ArrayList<>();
                res.add(list);
            } else {
                list = res.get(level);
            }
            list.add(node.val);

            levelOrder(node.left, level + 1);
            levelOrder(node.right, level + 1);
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}

